package q394;

import java.util.Objects;
import java.util.Stack;

/**
 * 394. 字符串解码
 */
public class Solution {


    public String decodeString(String s) {
        int start = -1;
        int end = -1;
        StringBuilder sb = new StringBuilder();
        int times = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                start = i;
                for (int j = i + 1; j < s.length(); j++) {
                    if (s.charAt(j) == '[') {
                        times = Integer.parseInt(s.substring(i, j));
                        i = j;
                        sb = new StringBuilder();
                        break;
                    }
                }
            } else if (s.charAt(i) == ']') {
                end = i + 1;
                StringBuilder sb1 = new StringBuilder();
                for (int j = 0; j < times; j++) {
                    sb1.append(sb);
                }
                sb = sb1;
                break;
            } else {
                sb.append(s.charAt(i));
            }
        }
        if (start != -1 && end != -1) {
            StringBuilder stringBuilder = new StringBuilder(s);
            StringBuilder replace = stringBuilder.replace(start, end, sb.toString());
            return decodeString(replace.toString());
        }
        return s;
    }



    public static void main(String[] args) {
        Solution solution = new Solution();
        String s = solution.decodeString("3[a]2[bc]");
        System.out.println(s);
    }

}
